/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import models.PersonalData;

/**
 *
 * @author Maciek
 */
public class SubjectNameFromCsr {
    
    public static final int PersonalDataDoesntMatch = 11;
    
    private String path(PersonalData pd){
        StringBuilder sb = new StringBuilder();
        sb.append("certs").append(File.separatorChar); 
        sb.append(pd.firstName).append(pd.lastName).append(pd.Pesel);
        return sb.toString();
    }
    
    private String buildgetSubjectCommand(String fileName){
        StringBuilder sb = new StringBuilder();
        sb.append("openssl req -in ").append(fileName);
        sb.append(" -noout -subject");
        return sb.toString();
    } 
    
    private String subjectNameRaw;
    
     
    private PersonalData getPersonalDataFromSubjectNameRaw(){
        String[] help = subjectNameRaw.split("CN=");  // w help[1] jest to co chcemy
        if(help.length!=2){
            System.err.println("Wystąpił bład w komunikacie : " + subjectNameRaw + " przy odzyskiwaniu RHS of CN=");
            return null;
        }
        
        String[] fields = help[1].split(" ");
        if(fields.length != 3){
            System.err.println("Wystąpił bład w komunikacie : " + subjectNameRaw + " za dużo danych odzielanych białym znakiem");
            return null;
        }
        
        return new PersonalData(fields[0], fields[1], fields[2], "0");
        
     }
    
    public int checkPersonalDataInCSR(PersonalData pd) throws IOException, InterruptedException{
        
        int procesResult = getSubjectName(pd);
        if( procesResult!= 0) return procesResult;
        
        boolean match =  pd.personalDataMatch(this.getPersonalDataFromSubjectNameRaw());
        if(match)
            return 0;
        else
            return SubjectNameFromCsr.PersonalDataDoesntMatch;
    }
    
    private int getSubjectName(PersonalData pd) throws IOException, InterruptedException{
         String fileName = path(pd) + ".csr";
         System.out.println("W pliku powinno się znajdować nasza prośba");
         String command = buildgetSubjectCommand(fileName);
         Process process = Runtime.getRuntime().exec(command);
         
         this.subjectNameRaw = getInput(process);
         System.out.println("SubjecteNameRaw : " + this.subjectNameRaw); 
         return process.waitFor();
    }
    
    
    
    public String getInput(Process proc) throws IOException{ // tu pożnaby zapisywać do jakiś plików
        InputStream stdout = proc.getInputStream();
        String line;
        InputStream stderr = proc.getErrorStream();
          BufferedReader brCleanUp =
        new BufferedReader (new InputStreamReader (stdout));
          
          StringWriter sw = new StringWriter();
          while ((line = brCleanUp.readLine ()) != null) {
            sw.write(line);
          }
          brCleanUp.close();

          // clean up if any output in stderr
          brCleanUp =
            new BufferedReader (new InputStreamReader (stderr));
          while ((line = brCleanUp.readLine ()) != null) {
            System.out.println ("[Stderr] " + line);
          }
          brCleanUp.close();
          
          return sw.toString();
    }
    
    public static void main(String args[]) throws Exception{
        PersonalData pd = new PersonalData("Maciej", "Zgliczynski" , "228", "00");
        SubjectNameFromCsr sn = new SubjectNameFromCsr();
        int retVal = sn.checkPersonalDataInCSR(pd);
        if(retVal == 0)
            System.out.println("Hura dziala");
        else{
            System.out.println("failed return value : " + retVal);
        }
    }
}
